<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Java,Thread,concurrent,JVM,HashMap,HashSet," />





  <link rel="alternate" href="/atom.xml" title="crossoverJie's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="背景上午刚到公司，准备开始一天的摸鱼之旅时突然收到了一封监控中心的邮件。
心中暗道不好，因为监控系统从来不会告诉我应用完美无 bug，其实系统挺猥琐。
打开邮件一看，果然告知我有一个应用的线程池队列达到阈值触发了报警。
由于这个应用出问题非常影响用户体验；于是立马让运维保留现场 dump 线程和内存同时重启应用，还好重启之后恢复正常。于是开始着手排查问题。">
<meta property="og:type" content="article">
<meta property="og:title" content="一次 HashSet 所引起的并发问题">
<meta property="og:url" content="http://crossoverjie.top/2018/11/08/java-senior/JVM-concurrent-HashSet-problem/index.html">
<meta property="og:site_name" content="crossoverJie's Blog">
<meta property="og:description" content="背景上午刚到公司，准备开始一天的摸鱼之旅时突然收到了一封监控中心的邮件。
心中暗道不好，因为监控系统从来不会告诉我应用完美无 bug，其实系统挺猥琐。
打开邮件一看，果然告知我有一个应用的线程池队列达到阈值触发了报警。
由于这个应用出问题非常影响用户体验；于是立马让运维保留现场 dump 线程和内存同时重启应用，还好重启之后恢复正常。于是开始着手排查问题。">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c669d9581.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c66f983e1.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c67e5a9b5.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c67c5e613.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c67e5a9b5.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c687f186c.jpg">
<meta property="og:updated_time" content="2019-05-07T17:56:08.128Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="一次 HashSet 所引起的并发问题">
<meta name="twitter:description" content="背景上午刚到公司，准备开始一天的摸鱼之旅时突然收到了一封监控中心的邮件。
心中暗道不好，因为监控系统从来不会告诉我应用完美无 bug，其实系统挺猥琐。
打开邮件一看，果然告知我有一个应用的线程池队列达到阈值触发了报警。
由于这个应用出问题非常影响用户体验；于是立马让运维保留现场 dump 线程和内存同时重启应用，还好重启之后恢复正常。于是开始着手排查问题。">
<meta name="twitter:image" content="https://i.loli.net/2019/05/08/5cd1c669d9581.jpg">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 555390,
      author: 'crossoverJie'
    }
  };
</script>




  <link rel="canonical" href="http://crossoverjie.top/2018/11/08/java-senior/JVM-concurrent-HashSet-problem/"/>

  <title> 一次 HashSet 所引起的并发问题 | crossoverJie's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  








  <div style="display: none;">
    <script src="https://s6.cnzz.com/stat.php?id=1259025147&web_id=1259025147" type="text/javascript"></script>
  </div>





  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">crossoverJie's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">baller</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-photo">
          <a href="/favourite" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />
            
            photo
          </a>
        </li>
      
        
        <li class="menu-item menu-item-jcsprout">
          <a href="https://crossoverjie.top/JCSprout/#/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-leaf"></i> <br />
            
            JCSprout
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cicada">
          <a href="https://github.com/TogetherOS/cicada" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-github"></i> <br />
            
            cicada
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cim">
          <a href="https://github.com/crossoverjie/cim" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-far fa-comment"></i> <br />
            
            CIM
          </a>
        </li>
      
        
        <li class="menu-item menu-item-vlog">
          <a href="https://space.bilibili.com/42339430" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-youtube"></i> <br />
            
            Vlog
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="#" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                一次 HashSet 所引起的并发问题
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-11-08T08:10:36+08:00" content="2018-11-08">
              2018-11-08
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Java-进阶/" itemprop="url" rel="index">
                    <span itemprop="name">Java 进阶</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/11/08/java-senior/JVM-concurrent-HashSet-problem/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/11/08/java-senior/JVM-concurrent-HashSet-problem/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/11/08/java-senior/JVM-concurrent-HashSet-problem/" class="leancloud_visitors" data-flag-title="一次 HashSet 所引起的并发问题">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
              &nbsp; | &nbsp;
              <span class="page-pv">本文总阅读量
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://i.loli.net/2019/05/08/5cd1c669d9581.jpg" alt=""></p>
<h1 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h1><p>上午刚到公司，准备开始一天的摸鱼之旅时突然收到了一封监控中心的邮件。</p>
<p>心中暗道不好，因为监控系统从来不会告诉我应用完美无 <code>bug</code>，其实系统挺猥琐。</p>
<p>打开邮件一看，果然告知我有一个应用的线程池队列达到阈值触发了报警。</p>
<p>由于这个应用出问题非常影响用户体验；于是立马让运维保留现场 <code>dump</code> 线程和内存同时重启应用，还好重启之后恢复正常。于是开始着手排查问题。</p>
<a id="more"></a>
<h1 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h1><p>首先了解下这个应用大概是做什么的。</p>
<p>简单来说就是从 <code>MQ</code> 中取出数据然后丢到后面的业务线程池中做具体的业务处理。</p>
<p>而报警的队列正好就是这个线程池的队列。</p>
<p>跟踪代码发现构建线程池的方式如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">ThreadPoolExecutor executor = <span class="keyword">new</span> ThreadPoolExecutor(coreSize, maxSize,</div><div class="line">              <span class="number">0L</span>, TimeUnit.MILLISECONDS,</div><div class="line">              <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;());;</div><div class="line">             put(poolName,executor);</div></pre></td></tr></table></figure>
<p>采用的是默认的 <code>LinkedBlockingQueue</code> 并没有指定大小（这也是个坑），于是这个队列的默认大小为 <code>Integer.MAX_VALUE</code>。</p>
<p>由于应用已经重启，只能从仅存的线程快照和内存快照进行分析。</p>
<h2 id="内存分析"><a href="#内存分析" class="headerlink" title="内存分析"></a>内存分析</h2><p>先利用 <code>MAT</code> 分析了内存，的到了如下报告。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c66f983e1.jpg" alt=""></p>
<p>其中有两个比较大的对象，一个就是之前线程池存放任务的 <code>LinkedBlockingQueue</code>，还有一个则是 <code>HashSet</code>。</p>
<p>当然其中队列占用了大量的内存，所以优先查看，<code>HashSet</code> 一会儿再看。</p>
<blockquote>
<p> 由于队列的大小给的够大，所以结合目前的情况来看应当是线程池里的任务处理较慢，导致队列的任务越堆越多，至少这是目前可以得出的结论。</p>
</blockquote>
<h2 id="线程分析"><a href="#线程分析" class="headerlink" title="线程分析"></a>线程分析</h2><p>再来看看线程的分析，这里利用 <a href="http://fastthread.io/index.jsp" target="_blank" rel="external">fastthread.io</a> 这个网站进行线程分析。</p>
<p>因为从表现来看线程池里的任务迟迟没有执行完毕，所以主要看看它们在干嘛。</p>
<p>正好他们都处于 <strong>RUNNABLE</strong> 状态，同时堆栈如下：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c67e5a9b5.jpg" alt=""></p>
<p>发现正好就是在处理上文提到的 <code>HashSet</code>，看这个堆栈是在查询 <code>key</code> 是否存在。通过查看 312 行的业务代码确实也是如此。</p>
<blockquote>
<p>这里的线程名字也是个坑，让我找了好久。</p>
</blockquote>
<h1 id="定位"><a href="#定位" class="headerlink" title="定位"></a>定位</h1><p>分析了内存和线程的堆栈之后其实已经大概猜出一些问题了。</p>
<p>这里其实有一个前提忘记讲到：</p>
<p>这个告警是<code>凌晨三点</code>发出的邮件，但并没有电话提醒之类的，所以大家都不知道。</p>
<p>到了早上上班时才发现并立即 <code>dump</code> 了上面的证据。</p>
<p>所有有一个很重要的事实：<strong>这几个业务线程在查询 <code>HashSet</code> 的时候运行了 6 7 个小时都没有返回</strong>。</p>
<p>通过之前的监控曲线图也可以看出：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c67c5e613.jpg" alt=""></p>
<p>操作系统在之前一直处于高负载中，直到我们早上看到报警重启之后才降低。</p>
<p>同时发现这个应用生产上运行的是 <code>JDK1.7</code> ，所以我初步认为应该是在查询 key 的时候进入了 <code>HashMap</code> 的环形链表导致 <code>CPU</code> 高负载同时也进入了死循环。</p>
<p>为了验证这个问题再次 review 了代码。</p>
<p>整理之后的伪代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//线程池</span></div><div class="line"><span class="keyword">private</span> ExecutorService executor;</div><div class="line"></div><div class="line"><span class="keyword">private</span> Set&lt;String&gt; set = <span class="keyword">new</span> hashSet();</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">execute</span><span class="params">()</span></span>&#123;</div><div class="line">	</div><div class="line">	<span class="keyword">while</span>(<span class="keyword">true</span>)&#123;</div><div class="line">		<span class="comment">//从 MQ 中获取数据</span></div><div class="line">		String key = subMQ();</div><div class="line">		executor.excute(<span class="keyword">new</span> Worker(key)) ;</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Worker</span> <span class="keyword">extends</span> <span class="title">Thread</span></span>&#123;</div><div class="line">	<span class="keyword">private</span> String key ;</div><div class="line"></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="title">Worker</span><span class="params">(String key)</span></span>&#123;</div><div class="line">		<span class="keyword">this</span>.key = key;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	<span class="meta">@Override</span></div><div class="line">	<span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span></span>&#123;</div><div class="line">		<span class="keyword">if</span>(!set.contains(key))&#123;</div><div class="line"></div><div class="line">			<span class="comment">//数据库查询</span></div><div class="line">			<span class="keyword">if</span>(queryDB(key))&#123;</div><div class="line">				set.add(key);</div><div class="line">				<span class="keyword">return</span>;</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line"></div><div class="line">		<span class="comment">//达到某种条件时清空 set</span></div><div class="line">		<span class="keyword">if</span>(flag)&#123;</div><div class="line">			set = <span class="keyword">null</span> ;</div><div class="line">		&#125;</div><div class="line">	&#125;	</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>大致的流程如下：</p>
<ul>
<li>源源不断的从 MQ 中获取数据。</li>
<li>将数据丢到业务线程池中。</li>
<li>判断数据是否已经写入了 <code>Set</code>。</li>
<li>没有则查询数据库。</li>
<li>之后写入到 <code>Set</code> 中。</li>
</ul>
<p>这里有一个很明显的问题，<strong>那就是作为共享资源的 Set 并没有做任何的同步处理</strong>。</p>
<p>这里会有多个线程并发的操作，由于 <code>HashSet</code> 其实本质上就是 <code>HashMap</code>，所以它肯定是线程不安全的，所以会出现两个问题：</p>
<ul>
<li>Set 中的数据在并发写入时被覆盖导致数据不准确。</li>
<li><strong>会在扩容的时候形成环形链表</strong>。</li>
</ul>
<p>第一个问题相对于第二个还能接受。</p>
<p>通过上文的内存分析我们已经知道这个 set 中的数据已经不少了。同时由于初始化时并没有指定大小，仅仅只是默认值，所以在大量的并发写入时候会导致频繁的扩容，而在 1.7 的条件下又可能会形成<strong>环形链表</strong>。</p>
<p>不巧的是代码中也有查询操作（<code>contains()</code>）,观察上文的堆栈情况：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c67e5a9b5.jpg" alt=""></p>
<p>发现是运行在 <code>HashMap</code> 的 465 行，来看看 1.7 中那里具体在做什么：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c687f186c.jpg" alt=""></p>
<p>已经很明显了。这里在遍历链表，同时由于形成了环形链表导致这个 <code>e.next</code> 永远不为空，所以这个循环也不会退出了。</p>
<p>到这里其实已经找到问题了，但还有一个疑问是为什么线程池里的任务队列会越堆越多。我第一直觉是任务执行太慢导致的。</p>
<p>仔细查看了代码发现只有一个地方可能会慢：也就是有一个<strong>数据库的查询</strong>。</p>
<p>把这个 SQL 拿到生产环境执行发现确实不快，查看索引发现都有命中。</p>
<p>但我一看表中的数据发现已经快有 <strong>7000W</strong> 的数据了。同时经过运维得知 <code>MySQL</code> 那台服务器的 <code>IO</code> 压力也比较大。</p>
<p>所以这个原因也比较明显了：</p>
<blockquote>
<p> 由于每消费一条数据都要去查询一次数据库，MySQL 本身压力就比较大，加上数据量也很高所以导致这个 IO 响应较慢，导致整个任务处理的就比较慢了。</p>
</blockquote>
<p>但还有一个原因也不能忽视；由于所有的业务线程在某个时间点都进入了死循环，根本没有执行完任务的机会，而后面的数据还在源源不断的进入，所以这个队列只会越堆越多！</p>
<p>这其实是一个老应用了，可能会有人问为什么之前没出现问题。</p>
<p>这是因为之前数据量都比较少，即使是并发写入也没有出现并发扩容形成环形链表的情况。这段时间业务量的暴增正好把这个隐藏的雷给揪出来了。所以还是得信墨菲他老人家的话。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>至此整个排查结束，而我们后续的调整措施大概如下：</p>
<ul>
<li><code>HashSet</code> 不是线程安全的，换为 <code>ConcurrentHashMap</code>同时把 <code>value</code> 写死一样可以达到 <code>set</code> 的效果。</li>
<li>根据我们后面的监控，初始化 <code>ConcurrentHashMap</code> 的大小尽量大一些，避免频繁的扩容。</li>
<li><code>MySQL</code> 中很多数据都已经不用了，进行冷热处理。尽量降低单表数据量。同时后期考虑分表。</li>
<li>查数据那里调整为查缓存，提高查询效率。</li>
<li>线程池的名称一定得取的有意义，不然是自己给自己增加难度。</li>
<li>根据监控将线程池的队列大小调整为一个具体值，并且要有拒绝策略。</li>
<li>升级到 <code>JDK1.8</code>。</li>
<li>再一个是报警邮件酌情考虑为电话通知😂。</li>
</ul>
<p><code>HashMap</code> 的死循环问题在网上层出不穷，没想到还真被我遇到了。现在要满足这个条件还是挺少见的，比如 1.8 以下的 <code>JDK</code> 这一条可能大多数人就碰不到，正好又证实了一次墨菲定律。</p>
<p>同时我会将文章更到这里，方便大家阅读和查询。</p>
<p><a href="https://crossoverjie.top/JCSprout/">https://crossoverjie.top/JCSprout/</a></p>
<p><strong>你的点赞与分享是对我最大的支持</strong></p>

      
    </div>

    <div>
      
        
<div id="wechat_subscriber" style="display: block； padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/weixinfooter1.jpg" alt="crossoverJie wechat" style="width: 200px; max-width: 100%;"/>
    <div>我很有眼光！</div>
</div>

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>请我吃🍗</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/weixin-reward-image.jpg" alt="crossoverJie WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/alipay-reward-image.jpg" alt="crossoverJie Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Java/" rel="tag">#Java</a>
          
            <a href="/tags/Thread/" rel="tag">#Thread</a>
          
            <a href="/tags/concurrent/" rel="tag">#concurrent</a>
          
            <a href="/tags/JVM/" rel="tag">#JVM</a>
          
            <a href="/tags/HashMap/" rel="tag">#HashMap</a>
          
            <a href="/tags/HashSet/" rel="tag">#HashSet</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/11/06/personal/1W-star-update/" rel="next" title="1.6W star 的 JCSprout 阅读体验大提升">
                <i class="fa fa-chevron-left"></i> 1.6W star 的 JCSprout 阅读体验大提升
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/11/12/java-senior/coding-online-analysis/" rel="prev" title="不改一行代码定位线上性能问题">
                不改一行代码定位线上性能问题 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            Overview
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/crossoverjie.jpg"
               alt="crossoverJie" />
          <p class="site-author-name" itemprop="name">crossoverJie</p>
          <p class="site-description motion-element" itemprop="description">You never know what you can do till you try.</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">116</span>
              <span class="site-state-item-name">posts</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">45</span>
                <span class="site-state-item-name">categories</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">109</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/crossoverJie" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/users/e2d07947c112/latest_articles" target="_blank" title="简书">
                  
                    <i class="fa fa-fw fa-book"></i>
                  
                  简书
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/576d4aaf7db2a20054ea4544" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-bookmark"></i>
                  
                  掘金
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/crossoverJie" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wuchong.me" title="Jark's Blog" target="_blank">Jark's Blog</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://tengj.top" title="嘟嘟独立博客" target="_blank">嘟嘟独立博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://yemengying.com/" title="Giraffe Home" target="_blank">Giraffe Home</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.jamespan.me/" title="潘小鶸(ruò)" target="_blank">潘小鶸(ruò)</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://fangjian0423.github.io/" title="Format's Notes" target="_blank">Format's Notes</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://yuzhouwan.com/" title="Benedict Jin" target="_blank">Benedict Jin</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.didispace.com/" title="程序猿DD" target="_blank">程序猿DD</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.52itstyle.vip/" title="小柒博客" target="_blank">小柒博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="Java技术驿站" target="_blank">Java技术驿站</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://vim.ink/" title="vim 教程网" target="_blank">vim 教程网</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.jitwxs.cn" title="jitwxs" target="_blank">jitwxs</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.javaboy.org" title="江南一点雨" target="_blank">江南一点雨</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.liangsonghua.me" title="松花皮蛋的黑板报" target="_blank">松花皮蛋的黑板报</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.fi-ads.com" title="Future iDeal" target="_blank">Future iDeal</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#背景"><span class="nav-number">1.</span> <span class="nav-text">背景</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#分析"><span class="nav-number">2.</span> <span class="nav-text">分析</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#内存分析"><span class="nav-number">2.1.</span> <span class="nav-text">内存分析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#线程分析"><span class="nav-number">2.2.</span> <span class="nav-text">线程分析</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#定位"><span class="nav-number">3.</span> <span class="nav-text">定位</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">crossoverJie</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

<div class="busuanzi-count">

  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span>人数</span>
  

  
    <span class="site-pv">您是第<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>位童鞋</span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'crossoverjie';
      var disqus_identifier = '2018/11/08/java-senior/JVM-concurrent-HashSet-problem/';
      var disqus_title = "一次 HashSet 所引起的并发问题";
      var disqus_url = 'http://crossoverjie.top/2018/11/08/java-senior/JVM-concurrent-HashSet-problem/';

      function run_disqus_script(disqus_script){
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');
      
        run_disqus_script('embed.js');
      
    </script>
  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';                
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });
                            
                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').mousedown(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("Qv6ckEtL1pe3PJD10qoOLKtg-gzGzoHsz", "NXiHFodQfmI8oxkK6IThhjrF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script type="text/javascript" src="/js/src/particle.js" count="50" zindex="-2" opacity="1" color="0,104,183"></script>
</body>
</html>
